import Vue from 'vue'
import Vuex from 'vuex'
import {
  getPrincipalInStore,
  removePrincipalInStore,
  removeTokenInCookie,
  setPrincipalInStore,
  setTokenInCookie
} from '@/common/js/auth'

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    isLogin: false,
    token: '',
    username: '未登录',
    noteId: -1,
    notebookId: -1,
    currentNote: {},
    trashNote: {},
    allTrashNotes: [],
    selectTags: [],
    allNotes: [],
    richText: '',
    user: getPrincipalInStore || {},
  },
  mutations: {
    setUsername(state, payload) {
      state.username = payload
    },
    setUser(state, user) {
      state.user = user;
    },
    SET_TOKEN(state, token) {
      state.token = token;
    },
    changeIsLogin(state, payload) {
      state.isLogin = payload
    },
    setNoteId(state, noteId) {
      state.noteId = noteId
    },
    setNotebookId(state, notebookId) {
      state.notebookId = notebookId
    },
    setCurrentNote(state, note) {
      state.currentNote = note
    },
    setSelectTags(state, selectTags) {
      state.selectTags = selectTags;
    },
    setAllNotes(state, notes) {
      state.allNotes = notes
    },
    setTrashNote(state, note) {
      state.trashNote = note
    },
    setAllTrashNotes(state, notes) {
      state.allTrashNotes = notes
    },
    setRichText(state, rich) {
      state.richText = rich
    }
  },
  getters: {},
  actions: {

    //根据用户名登录
    LoginByUsername({commit}, data) {
      console.log(data);
      commit('SET_TOKEN', data.token);
      setTokenInCookie(data.token);
      commit('setUser', data.principal);
      // 放到缓存中
      setPrincipalInStore(data.principal);
      commit('setUsername', data.principal.username);
    },

    //校验用户是否登录
    checkLoginStatus({commit}) {
      this.$Loading.start();
      let principal = getPrincipalInStore();
      if (principal) {
        commit('changeIsLogin', true);
        commit('setUser', principal);
        commit('setUsername', principal.username);
        this.$Loading.finish();
      } else {
        this.$Message.error('没有权限-请先登录');
        this.$router.push('/login');
      }
    },

    //注销session
    FedLogOut({commit}) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '');
        commit('changeIsLogin', false);
        commit('setUsername', '未登录');
        commit('setUser', null);
        // 删除Cookie用户
        removeTokenInCookie();
        // 删除用户缓存
        removePrincipalInStore();
        resolve()
      })
    },
  }
});

export default store
